package cn.leonis.leetcode;

import java.util.Arrays;

/**
 * @Author Tobi
 * @Date 2021-07-22 下午9:05
 * 有效的字母亿维此
 */
public class ValidAnagramSolution {

    public static void main(String[] args) {
        String s = "anagram";
        String t = "nagaram";
        ValidAnagramSolution solution = new ValidAnagramSolution();
        System.out.println(solution.isAnagram1(s, t));
    }

    /**
     * 解法一：先将字符串转换为数组，然后数组排序再对比
     * @param s
     * @param t
     * @return
     */
    public boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) {
            return false;
        }
        char[] sc = s.toCharArray();
        char[] tc = t.toCharArray();
        Arrays.sort(sc);
        Arrays.sort(tc);
        return Arrays.equals(sc, tc);
    }

    /**
     * 解法二：使用哈希表
     * @param s
     * @param t
     * @return
     */
    public boolean isAnagram1(String s, String t) {
        if (s.length() != t.length()) {
            return false;
        }

        int[] tables = new int[26];
        for (int i = 0; i < s.length(); i++) {
            tables[s.charAt(i) - 'a']++;
        }
        for (int i = 0; i < t.length(); i++) {
            tables[t.charAt(i) - 'a']--;
            if (tables[t.charAt(i) - 'a'] < 0) {
                return false;
            }
        }

        return true;
    }
}
